<template>
  <div class="tinymce-editor">
    <editor ref="mytextarea" class="mytextarea" v-model="myValue" :init="init" :disabled="!isEditor">
    </editor>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import { uploadImage } from "@/api/gwoper/news";
  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  // import 'tinymce/themes/modern/theme'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/advlist'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/imagetools'// 图片编辑工具
  import 'tinymce/plugins/axupimgs' // 多图片上传
  import 'tinymce/plugins/media' // 插入/编辑媒体文件
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/textcolor' // 文本颜色
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/fullscreen' // 全屏插件
  import 'tinymce/plugins/code'// 查看源码
  import 'tinymce/plugins/anchor' // 锚点插件
  import 'tinymce/plugins/autolink' // 自动创建超链接autosave
  import 'tinymce/plugins/autosave' // 恢复到上次自动保存的数据
  import 'tinymce/plugins/paste' // 粘贴为纯文本
  import 'tinymce/plugins/link' // 链接
  import 'tinymce/plugins/charmap' // 特殊符号
  // import 'tinymce/plugins/emoticons' // 表情
  import 'tinymce/plugins/hr'// 水平线
  import 'tinymce/plugins/pagebreak' // 分页符
  import 'tinymce/plugins/insertdatetime' // 插入时间
  import 'tinymce/plugins/autosave' // 打印
  import 'tinymce/plugins/print' // 粘贴为纯文本
  import 'tinymce/plugins/preview' // 预览
  import 'tinymce/plugins/bdmap' // 地图
  import 'tinymce/plugins/indent2em' // 首行缩进
  // import 'tinymce/plugins/formatpainter' // 格式刷
  import 'tinymce/icons/default'

  export default {
    name: 'TinymceEditor',
    components: {
      Editor
    },
    props: {
      //传入一个value，使组件支持v-model绑定
      editValue: {
        type: [String, Array, Object, Number, Boolean]
      },
      isEdit: {
        type: [Boolean]
      },
      menubar: {
        type: [String, Array],
        //启用菜单栏并显示如下项 [文件 编辑 插入 格式 表格]
        default: 'file edit insert view format table'
      },
      plugins: {
        type: [String, Array],
        default: 'lists advlist image imagetools axupimgs media table textcolor wordcount contextmenu fullscreen code anchor autolink autosave paste link charmap hr pagebreak insertdatetime print preview bdmap indent2em'
      },
      toolbar: {
        type: [String, Array],
        default: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
        styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
        table image media charmap hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight axupimgs '
      },
      font_formats: {
        type: [String, Array],
        default: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats',
      },
      fontsize_formats: {
        type: [String, Array],
        default: '10px 11px 12px 13px 14px 15px 16px 17px 18px 19px 20px 21px 22px 23px 24px 36px 48px 56px 72px'
      },
    },
    data() {
      return {
        imgUrlAction:
          process.env.VUE_APP_BASE_API + "/operation-center/information/uploadImageForWangEditor", // 上传接口
        headers: {
          Authorization: "Bearer " + getToken()
        },
        myValue: this.editValue,
        isEditor: this.isEdit,
        //初始化配置
        init: {
          selector: '.mytextarea',
          height: 500, //编辑器高度
          min_height: 400,
          language_url: '/tinymce/langs/zh_CN.js',
          language: 'zh_CN',// 汉化语言
          auto_focus: true, // 自动获取焦点
          menubar: this.methods, // 指定菜单栏
          plugins: this.plugins,// 指定需加载的插件
          toolbar: this.toolbar, // 指定工具栏
          branding: false,// 隐藏右下角技术支持
          font_formats: this.font_formats, // 所有字体
          fontsize_formats: this.fontsize_formats,// 文字大小
          lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 2',// 行高列表
          toolbar_mode: 'sliding', // 工具栏模式
          media_live_embeds: true,
          object_resizing: true, // 开启大小调整
          importcss_append: true,// 模框可移动
          toolbar_sticky: true,
          draggable_modal: true,
          autosave_ask_before_unload: false,
          //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
          //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
          images_upload_handler: (blobInfo, succFun, failFun) => {
            let fd = new FormData();
            fd.append('multipartFile', blobInfo.blob()); // 上传的文件： 键名，键值
            // 以下是上传图片的接口，视情况而更改就可以啦
            uploadImage(fd).then(res => {
              console.log(res)
              succFun(res.data[0].url)
            }).catch(err=>{
              console.log(err)
            })
          },
          file_picker_callback: (callback, value, meta)=> {
            let that = this;
            if(meta.filetype == 'media'){
              let input = document.createElement('input');//创建一个隐藏的input
              input.setAttribute('type', 'file');
              input.setAttribute("accept", "video/mp4,video/AVI,video/mov,video/FLV,video/rmvb,video/mtv,video/mpeg");

              input.onchange = function(){
                let file = this.files[0]
                let ext = file.name.split(".")[1];
                if (
                  ext !== "mp4" &&
                  ext !== "AVI"&&
                  ext !== "mov"&&
                  ext !== "FLV"&&
                  ext !== "rmvb"&&
                  ext !== "wmv"&&
                  ext !== "mtv"&&
                  ext !== "mpg"&&
                  ext !== "mpeg"

                ) {
                  that.$message.error({message:'上传资源只能是 AVI/mov/rmvb/FLV/mp4/wmv/mtv/mpg/mpeg 格式的视频!',duration:5000,customClass:'zZindex'});
                  return false;
                }
                console.log(this.files[0])
                let fd = new FormData();
                fd.append('multipartFile', file);// 上传的文件： 键名，键值
                uploadImage(fd).then(res => {
                  console.log(res)
                  callback(res.data[0].url, { title: file.name }) //将url显示在弹框输入框中
                }).catch(err=>{
                  console.log(err)
                })
              }
              //触发点击
              input.click();
            }
            if(meta.filetype == 'image'){
              let input = document.createElement('input');//创建一个隐藏的input
              input.setAttribute('type', 'file');
              input.onchange = function(){
                let file = this.files[0]
                let ext = file.name.split(".")[1];
                let fd = new FormData();
                fd.append('multipartFile', file);// 上传的文件： 键名，键值
                uploadImage(fd).then(res => {
                  console.log(res)
                  callback(res.data[0].url, { title: file.name }) //将url显示在弹框输入框中
                }).catch(err=>{
                  console.log(err)
                })
              }
              //触发点击
              input.click();

            }
          },
        },
      }
    },
    mounted() {
      tinymce.init({})
    },
    watch: {
      editValue(newValue) {
        this.myValue = newValue
      },
      myValue(newValue) {
        this.$emit('changeEditor', newValue);
      },
      isEdit(newValue) {
        this.isEditor = newValue;
      },
    },
  }

</script>
<style scoped lang="scss">
  @import '../../assets/tinymce/skins/ui/oxide/skin.css';

  .w-e-text-container .w-e-text table {
    border: 1px solid #000000;
    border-collapse: collapse;
  }
</style>
